package com.xiangfei.weixin.controller;

import com.xiangfei.weixin.utils.CheckUtil;
import com.xiangfei.weixin.utils.MessageUtil;
import com.xiangfei.weixin.utils.TextMessageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@Controller
public class LoginController {

    @RequestMapping(value = "wx",method= RequestMethod.GET)
    public void login(HttpServletRequest request, HttpServletResponse response){
        System.out.println("success");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        System.out.println("signature:"+signature);
        System.out.println("echostr:"+echostr);
        PrintWriter out = null;

        try {
            out = response.getWriter();
            if(CheckUtil.checkSignature(signature, timestamp, nonce)){
                out.write(echostr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            out.close();
        }
    }

    @RequestMapping(value = "wx",method=RequestMethod.POST)
    public void dopost(HttpServletRequest request, HttpServletResponse response){

        response.setCharacterEncoding("utf-8");
        PrintWriter out = null;
        Map<String,String> map = MessageUtil.xmlToMap(request);

        String ToUserName = map.get("ToUserName");
        String FromUserName = map.get("FromUserName");
        String MsgType = map.get("MsgType");
        String Content = map.get("Content");

        String message = null;
        if ("text".equals(MsgType)){
            TextMessageUtil textMessage = new TextMessageUtil();
            if ("1".equals(Content)){
                message = textMessage.initMessage(FromUserName, ToUserName);
            } else {
                message = textMessage.initMessage(FromUserName, ToUserName, Content);
            }
        }
        try {
            out = response.getWriter();
            out.write(message);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

}
